package org.zcl.sqlserver.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.zcl.sqlserver.config.SyncCouponProperties;
import org.zcl.sqlserver.entity.Coupon;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * .
 *
 * @author zhuchenglin
 * @since 2024/10/24 13:45
 */
@Service
public class SyncConfigService {
    public static final int ASYNC_COUPON_SIZE = 10000;

    @Autowired
    @Qualifier("asyncCoupon")
    private Executor asyncCouponExecutor;

    @Autowired
    private SyncCouponProperties syncCouponProperties;


    public void printConfig() {
        List<SyncCouponProperties.CouponConfig> coupons = syncCouponProperties.getCouponConfigs();
        for (SyncCouponProperties.CouponConfig coupon : coupons) {
            System.out.println("Brand: " + coupon.getBrand());
            System.out.println("URL: " + coupon.getUrl());
            System.out.println("Schema Name: " + coupon.getSchemaName());
        }
    }

    public SyncCouponProperties.CouponConfig getCouponConfigByBrand(String brand) {
        return syncCouponProperties.getCouponConfigs().stream()
                .filter(coupon -> coupon.getBrand().equalsIgnoreCase(brand))
                .findFirst()
                .orElse(null);
    }

    public void testSync(int size) {
        List<List<Coupon>> list = init(size);
        for (List<Coupon> coupons : list) {
            asyncCouponExecutor.execute(() -> {
                testThreadPool(coupons);
            });
        }
        // 等待所有任务完成
        System.out.println("end");
    }

    private List<List<Coupon>> init(int size) {
        List<Coupon> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            Coupon coupon = new Coupon();
            coupon.setName("coupon" + i);
            list.add(coupon);
        }
        return partitionList(list);
    }

    protected void testThreadPool(List<Coupon> list) {
        for (int i = 0; i < list.size(); i++) {
            Coupon coupon = list.get(i);
            coupon.setCouponId(String.valueOf(i));
        }
        System.out.println(Thread.currentThread() + "-----" + JSON.toJSONString(list));
    }

    protected <T> List<List<T>> partitionList(List<T> list) {
        List<List<T>> batches = new ArrayList<>();
        int batchSize = ASYNC_COUPON_SIZE;
        for (int i = 0; i < list.size(); i += batchSize) {
            batches.add(list.subList(i, Math.min(i + batchSize, list.size())));
        }
        return batches;
    }
}
